<template>
  <div class="data-detail-container">
    <div v-loading="loading" class="content-container">
      <!-- 面包屑 -->
      <div class="breadcrumb-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: currentRoutePath }">
            {{ currentRouteName }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ detailData.catalogName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 主卡片 -->
      <div shadow="never" class="main-card">
        <!-- <template #header> -->
        <div class="card-header">
          <div class="header-top">
            <div class="header-content">
              <span class="dataset-type">{{ detailData.menuName || '数据集' }}</span>
              <h2 class="dataset-title">{{ detailData.catalogName }}</h2>
            </div>

            <div class="header-actions">
              <!-- <div class="action-item">
              <img src="@/assets/imgs/detail/search.png" />
              <span>数据预览</span>
            </div> -->

              <!-- <div class="action-item">
                <img src="@/assets/imgs/detail/sc.png" />
                <span>{{ detailData.collected ? '已收藏' : '收藏' }}</span>
              </div> -->

              <div class="action-item" v-if="showInterface && isLogin">
                <img src="@/assets/imgs/detail/apply.svg" />
                <!-- <span @click="openApplyDialog">{{ applyStatusText }}</span> -->
                <span v-if="detailData.interfaceStatus == null" @click="openApplyDialog"
                  >申请使用 {{ detailData.interfaceStatus }}</span
                >
                <span
                  @click="openSharedApplyDialog('3', 'view')"
                  v-if="
                    detailData.interfaceStatus == '1' ||
                    detailData.interfaceStatus == '2' ||
                    detailData.interfaceStatus == '4'
                  "
                  >查看 ( <span v-if="detailData.interfaceStatus == '1'">已提交</span>
                  <span v-if="detailData.interfaceStatus == '2'">审核中</span>
                  <span v-if="detailData.interfaceStatus == '4'">审核通过</span>
                  )
                </span>
                <span
                  @click="openSharedApplyDialog('3', 'submit')"
                  v-if="detailData.interfaceStatus == '0' || detailData.interfaceStatus == '3'"
                  >查看( <span v-if="detailData.interfaceStatus == '0'">未提交</span>
                  <span v-if="detailData.interfaceStatus == '3'">审核不通过</span>
                  )
                </span>
              </div>
            </div>
          </div>
          <div class="header-bottom">
            <!-- <div class="bottom-item">
            <img src="@/assets/imgs/detail/time.png" />
            <span>数据量：{{ detailData.dataCount || '暂无数据' }}</span>
          </div> -->
            <div class="bottom-item">
              <img src="@/assets/imgs/detail/time.png" />
              <span>数据更新时间：{{ detailData.updateTime || '暂无数据' }}</span>
            </div>
            <div class="bottom-item">
              <img src="@/assets/imgs/detail/time.png" />
              <span>查看：{{ detailData.viewNum || '0' }}次</span>
            </div>
          </div>
        </div>

        <!-- </template> -->

        <!-- 基本信息 -->
        <div class="basic-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="目录编码">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/1.png"
                    style="width: 16px; height: 16px"
                    alt="目录编码"
                  />
                  <span>目录编码</span>
                </div> </template
              ><div class="summary">
                {{ detailData.catalogCode || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="目录分类名称">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/2.png"
                    style="width: 16px; height: 16px"
                    alt="目录分类名称"
                  />
                  <span>目录分类名称</span>
                </div> </template
              ><div class="summary">
                {{ detailData.menuName || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="目录名称">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/3.png"
                    style="width: 16px; height: 16px"
                    alt="目录名称"
                  />
                  <span>目录名称</span>
                </div> </template
              ><div class="summary">
                {{ detailData.catalogName || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="共享属性">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/4.png"
                    style="width: 16px; height: 16px"
                    alt="共享属性"
                  />
                  <span>共享属性</span>
                </div> </template
              ><div class="summary">
                {{ getShareTypeLabel || detailData.shareProperty || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="数源部门名称">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/5.png"
                    style="width: 16px; height: 16px"
                    alt="数源部门名称"
                  />
                  <span>数源部门名称</span>
                </div> </template
              ><div class="summary">
                {{ detailData.deptName || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/6.png"
                    style="width: 16px; height: 16px"
                    alt="更新时间"
                  />
                  <span>更新时间</span>
                </div> </template
              ><div class="summary">
                {{ detailData.updateTime || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="应用场景">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/7.png"
                    style="width: 16px; height: 16px"
                    alt="应用场景"
                  />
                  <span>应用场景</span>
                </div> </template
              ><div class="summary">
                {{ detailData.applyScene || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="提供渠道">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/8.png"
                    style="width: 16px; height: 16px"
                    alt="提供渠道"
                  />
                  <span>提供渠道</span>
                </div> </template
              ><div class="summary">
                {{ detailData.channel || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="所属领域">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/9.png"
                    style="width: 16px; height: 16px"
                    alt="所属领域"
                  />
                  <span>所属领域</span>
                </div> </template
              ><div class="summary">
                {{ detailData.domain || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="更新频率">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/10.png"
                    style="width: 16px; height: 16px"
                    alt="更新频率"
                  />
                  <span>更新频率</span>
                </div> </template
              ><div class="summary">
                {{ detailData.periodType || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="目录摘要">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/11.png"
                    style="width: 16px; height: 16px"
                    alt="目录摘要"
                  />
                  <span>目录摘要</span>
                </div> </template
              ><div class="summary">
                {{ detailData.abstractInfo || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="业务领域">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/12.png"
                    style="width: 16px; height: 16px"
                    alt="业务领域"
                  />
                  <span>业务领域</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.businessDomain || detailData.businessDomain || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="主题类型">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/13.png"
                    style="width: 16px; height: 16px"
                    alt="主题类型"
                  />
                  <span>主题类型</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.subjectType || detailData.subjectType || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="主题特征">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/1.png"
                    style="width: 16px; height: 16px"
                    alt="主题特征"
                  />
                  <span>主题特征</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.subjectFeature || detailData.subjectFeature || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="行业分类">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/2.png"
                    style="width: 16px; height: 16px"
                    alt="行业分类"
                  />
                  <span>行业分类</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.industryClass || detailData.industryClass || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="业务分类">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/3.png"
                    style="width: 16px; height: 16px"
                    alt="业务分类"
                  />
                  <span>业务分类</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.businessClass || detailData.businessClass || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="管理对象分类">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/4.png"
                    style="width: 16px; height: 16px"
                    alt="管理对象分类"
                  />
                  <span>管理对象分类</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.manageObjClass || detailData.manageObjClass || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="主题分类">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/5.png"
                    style="width: 16px; height: 16px"
                    alt="主题分类"
                  />
                  <span>主题分类</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.topicClass || detailData.topicClass || '暂无信息' }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="信息类别分类">
              <template #label>
                <div style="display: flex; align-items: center; gap: 6px">
                  <img
                    src="@/assets/imgs/detail/6.png"
                    style="width: 16px; height: 16px"
                    alt="信息类别分类"
                  />
                  <span>信息类别分类</span>
                </div> </template
              ><div class="summary">
                {{ dictLabels.infoCategoryClass || detailData.infoCategoryClass || '暂无信息' }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 数据目录 数据资源 -->
        <template v-if="showDataCatalog">
          <div class="title-data">
            <div class="border-left"></div>
            <h3>数据资源</h3>
          </div>
          <div v-if="!isLogin" class="no-login-tip">
            <div class="tip-content">
              <!-- <img src="@/assets/imgs/detail/login.png" alt="请登录" class="login-icon" /> -->
              <p>请登录后查看相关数据</p>
              <!-- <el-button type="primary" @click="redirectToLogin">立即登录</el-button> -->
            </div>
          </div>

          <div v-else>
            <div class="data-resource-section">
              <div class="resource-content">
                <div class="resource-item">
                  <div class="resource-item-son">
                    <img src="@/assets/imgs/detail/time.png" />
                    <span style="color: #333333">库表ETL</span>
                  </div>
                  <el-tag>通过库表ETL任务同步数据</el-tag>
                </div>
                <div class="resource-item">
                  <div class="resource-item-son">
                    <!-- 根据 otherResource.1 的值显示不同内容 -->
                    <template v-if="[null].includes(detailData.otherResource?.['1'])">
                      <span style="color: #ff6600; cursor: pointer" @click="openApplyDataModal">
                        提交申请
                      </span>
                    </template>
                    <template v-if="['0', '3'].includes(detailData.otherResource?.['1'])">
                      <span
                        style="color: #ff6600; cursor: pointer"
                        @click="openSharedApplyDialog('1', 'submit')"
                      >
                        提交
                        <span style="color: #009eff">
                          (
                          <span v-if="detailData.otherResource?.['1'] == '0'"
                            >已保存，暂未提交</span
                          >
                          <span v-if="detailData.otherResource?.['1'] == '3'">审核未通过</span>)
                        </span>
                      </span>
                    </template>
                    <template v-else-if="['1', '2', '4'].includes(detailData.otherResource?.['1'])">
                      <span
                        style="color: #666666; cursor: pointer"
                        @click="openSharedApplyDialog('1', 'view')"
                      >
                        查看
                        <span style="color: #009eff"
                          >(
                          <span v-if="detailData.otherResource?.['1'] == '1'">已提交</span>
                          <span v-if="detailData.otherResource?.['1'] == '2'">审核中</span>
                          <span v-if="detailData.otherResource?.['1'] == '4'">审核通过</span>
                          )
                        </span>
                      </span>
                    </template>
                  </div>
                </div>
              </div>
            </div>
            <div class="data-resource-section">
              <div class="resource-content">
                <div class="resource-item">
                  <div class="resource-item-son">
                    <img src="@/assets/imgs/detail/time.png" />
                    <span style="color: #333333">数据集</span>
                  </div>
                  <el-tag>XLS</el-tag>
                  <el-tag>CSV</el-tag>
                  <el-tag>JSON</el-tag>
                </div>
                <div class="resource-item">
                  <div class="resource-item-son" style="margin-right: 10px">
                    <span style="color: #009eff"
                      >下载次数：{{ detailData.otherResource?.['2'] || 0 }}</span
                    >
                  </div>
                  <div class="resource-item-son">
                    <!-- <img src="@/assets/imgs/detail/time.png" /> -->
                    <span style="color: #666666; cursor: pointer" @click="toDatasetDetail"
                      >查看</span
                    >
                  </div>
                </div>
              </div>
            </div>
            <!-- 只有当 otherResource 中有 3 字段时才显示数据接口部分 -->
            <div
              v-if="detailData.otherResource && '3' in detailData.otherResource"
              class="data-resource-section"
            >
              <div class="resource-content">
                <div class="resource-item">
                  <div class="resource-item-son">
                    <img src="@/assets/imgs/detail/time.png" />
                    <span style="color: #333333">数据接口</span>
                  </div>
                  <el-tag>API</el-tag>
                </div>
                <div class="resource-item">
                  <div class="resource-item-son" style="margin-right: 10px">
                    <span style="color: #009eff"
                      >下载次数：{{ detailData.otherResource?.['3'] || 0 }}</span
                    >
                  </div>
                  <div class="resource-item-son">
                    <!-- <img src="@/assets/imgs/detail/dw.png" /> -->
                    <span style="color: #666666; cursor: pointer" @click="toInterfaceDetail">
                      查看</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 数据集 数据下载 -->
        <template v-if="showDataset">
          <div class="title-data">
            <div class="border-left"></div>
            <h3>数据下载</h3>
          </div>
          <div v-if="!isLogin" class="no-login-tip">
            <div class="tip-content">
              <!-- <img src="@/assets/imgs/detail/login.png" alt="请登录" class="login-icon" /> -->
              <p>请登录后查看相关数据</p>
              <!-- <el-button type="primary" @click="redirectToLogin">立即登录</el-button> -->
            </div>
          </div>
          <div v-else class="dataset-table-section">
            <!-- <div style="margin-bottom: 16px">
              <el-button type="primary" @click="handleApplyDownloadAll">
                申请下载全部文件
              </el-button>
            </div> -->
            <div class="preview-section">
              <el-table :data="datasetList" style="width: 100%" :span-method="objectSpanMethod">
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="dataSourceName" label="文件名称" align="center" />
                <el-table-column
                  prop="fileFormatLabel"
                  label="文件格式"
                  align="center"
                  width="120"
                />
                <el-table-column prop="num" label="下载量" width="100" align="center" />
                <el-table-column label="操作" width="250" align="center">
                  <template #default="scope">
                    <el-button
                      v-if="scope.row.status == null"
                      link
                      type="primary"
                      @click="handleApplyDownloadAll"
                    >
                      提交申请下载
                    </el-button>
                    <el-button
                      v-if="scope.row.status == '0' || scope.row.status == '3'"
                      link
                      type="primary"
                      @click="openSharedApplyDialog('2', 'submit')"
                    >
                      申请下载
                      <span v-if="scope.row.status != null">
                        ( <span v-if="scope.row.status == '0'">已保存，暂未提交</span>
                        <span v-else-if="scope.row.status == '3'">审核未通过</span>)
                      </span>
                    </el-button>
                    <el-button
                      v-if="
                        scope.row.status == '1' ||
                        scope.row.status == '2' ||
                        scope.row.status == '4'
                      "
                      link
                      type="primary"
                      @click="openSharedApplyDialog('2', 'view')"
                    >
                      查看申请详情
                      <span>
                        ( <span v-if="scope.row.status == '1'">已提交</span>
                        <span v-else-if="scope.row.status == '2'">审核中</span>
                        <span v-else-if="scope.row.status == '4'">审核通过</span>)
                      </span>
                    </el-button>
                    <el-button
                      v-if="scope.row.status == '4'"
                      link
                      type="primary"
                      @click="downloadFile(scope.row)"
                    >
                      下载
                      <span>
                        (
                        <span v-if="scope.row.status == '4'">审核通过</span>)
                      </span>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>

        <!--  数据接口  -->
        <template v-if="showInterface">
          <div class="title-data">
            <div class="border-left"></div>
            <h3>接口调用指导</h3>
          </div>

          <div class="calling-guide-section">
            <div class="step-item">
              <div class="step-number">1</div>
              <div class="step-content">
                <p>登录平台</p>
              </div>
              <div class="step-arrow"></div>
            </div>
            <div class="step-item">
              <div class="step-number">2</div>
              <div class="step-content">
                <p>提交申请</p>
              </div>
              <div class="step-arrow"></div>
            </div>
            <div class="step-item">
              <div class="step-number">3</div>
              <div class="step-content">
                <p>平台分配鉴权信息</p>
              </div>
              <div class="step-arrow"></div>
            </div>
            <div class="step-item">
              <div class="step-number">4</div>
              <div class="step-content">
                <p>使用接口</p>
              </div>
            </div>
          </div>

          <!-- 接口信息 -->
          <div class="title-data">
            <div class="border-left"></div>
            <h3>接口信息</h3>
          </div>
          <div v-if="!isLogin" class="no-login-tip">
            <div class="tip-content">
              <!-- <img src="@/assets/imgs/detail/login.png" alt="请登录" class="login-icon" /> -->
              <p>请登录后查看相关数据</p>
              <!-- <el-button type="primary" @click="redirectToLogin">立即登录</el-button> -->
            </div>
          </div>
          <template v-else>
            <div class="basic-info">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="服务地址">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/1.png"
                        style="width: 16px; height: 16px"
                        alt="服务地址"
                      />
                      <span>服务地址</span>
                    </div> </template
                  ><div class="summary" v-if="detailData.interfaceStatus === '4'">
                    {{ detailDatas.serviceUrl || '-' }}
                  </div>
                  <div v-else>
                    <div class="tip-content" style="color: gray">
                      <p> 数据需等审核通过显示 </p>
                    </div>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="接口路径">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/2.png"
                        style="width: 16px; height: 16px"
                        alt="接口路径"
                      />
                      <span>接口路径</span>
                    </div> </template
                  ><div class="summary">
                    {{ detailDatas.interfacePath || '-' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="接口类型">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/3.png"
                        style="width: 16px; height: 16px"
                        alt="接口类型"
                      />
                      <span>接口类型</span>
                    </div> </template
                  ><div class="summary">
                    {{ detailDatas.interfaceType || 'RESTful API' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="接口方法">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/4.png"
                        style="width: 16px; height: 16px"
                        alt="接口方法"
                      />
                      <span>接口方法</span>
                    </div> </template
                  ><div class="summary">
                    {{ interfaceMethodLabel || 'GET' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="接口编码">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/5.png"
                        style="width: 16px; height: 16px"
                        alt="接口编码"
                      />
                      <span>接口编码</span>
                    </div> </template
                  ><div class="summary">
                    {{ detailDatas.interfaceCode || 'API001' }}
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="Content-Type">
                  <template #label>
                    <div style="display: flex; align-items: center; gap: 6px">
                      <img
                        src="@/assets/imgs/detail/6.png"
                        style="width: 16px; height: 16px"
                        alt="Content-Type"
                      />
                      <span>Content-Type</span>
                    </div> </template
                  ><div class="summary">
                    {{ detailDatas.contentType || '-' }}
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>

          <!-- 请求参数 -->
          <div class="title-data">
            <div class="border-left"></div>
            <h3>请求参数</h3>
          </div>

          <!-- 接口信息 -->
          <div v-if="!isLogin" class="no-login-tip">
            <div class="tip-content">
              <!-- <img src="@/assets/imgs/detail/login.png" alt="请登录" class="login-icon" /> -->
              <p>请登录后查看相关数据</p>
              <!-- <el-button type="primary" @click="redirectToLogin">立即登录</el-button> -->
            </div>
          </div>

          <div v-else class="request-params-section">
            <div style="text-align: right; margin: 10px 0"
              ><el-button type="primary" @click="testOnlineInterface">测试接口</el-button></div
            >
            <div v-if="formattedRequestParams" class="code-block">
              <pre><code>{{ formattedRequestParams }}</code></pre>
            </div>
            <div v-else class="no-data">暂无请求参数示例</div>
          </div>

          <!-- 返回参数 -->
          <div class="title-data">
            <div class="border-left"></div>
            <h3>返回参数</h3>
          </div>

          <div v-if="!isLogin" class="no-login-tip">
            <div class="tip-content">
              <!-- <img src="@/assets/imgs/detail/login.png" alt="请登录" class="login-icon" /> -->
              <p>请登录后查看相关数据</p>
              <!-- <el-button type="primary" @click="redirectToLogin">立即登录</el-button> -->
            </div>
          </div>
          <div v-else class="response-params-section">
            <div v-if="formattedResponseParams" class="code-block">
              <pre><code>{{ formattedResponseParams }}</code></pre>
            </div>
            <div v-else class="no-data">暂无返回参数示例</div>
          </div>
        </template>

        <div class="title-data">
          <div class="border-left"></div>
          <h3>数据项</h3>
        </div>
        <!-- 数据预览 -->
        <div class="preview-section">
          <el-table :data="previewData" style="width: 100%">
            <el-table-column
              align="center"
              v-for="column in columns"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :formatter="column.formatter"
            />
          </el-table>
          <!-- 添加分页组件 -->
          <div
            class="pagination-container"
            style="margin-top: 16px; display: flex; justify-content: flex-end"
          >
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      <!-- 添加测试接口弹窗 -->
      <el-dialog
        v-model="testDialogVisible"
        title="测试接口"
        width="800px"
        :before-close="() => (testDialogVisible = false)"
      >
        <div class="test-dialog-content">
          <div class="dialog-section">
            <h4>请求参数</h4>
            <div v-if="Object.keys(testParams).length > 0" class="params-editor">
              <div v-for="(value, key) in testParams" :key="key" class="param-item">
                <span class="param-name">{{ key }}:</span>
                <el-input
                  v-model="testParams[key]"
                  :placeholder="`请输入${key}的值`"
                  :type="typeof value === 'number' ? 'number' : 'text'"
                />
              </div>
            </div>
            <div v-else class="no-params">暂无请求参数</div>
          </div>

          <div class="dialog-section">
            <h4>测试结果</h4>
            <div v-if="testResult" class="result-container">
              <pre>{{ testResult }}</pre>
            </div>
            <div v-else-if="testLoading" class="loading">测试中...</div>
            <div v-else class="no-result">暂无测试结果</div>
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="testDialogVisible = false">取消</el-button>
            <el-button type="primary" :loading="testLoading" @click="submitTest"> 测试 </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 引入申请数据组件 -->
      <ApplyDataModal
        @formSubmitted="handleFormSubmitted"
        ref="applyDataModalRef"
        :data-info="detailData"
      />

      <!-- 引入下载协议组件 -->
      <DownloadAgreementModal
        @formSubmitted="handleFormSubmitted"
        ref="downloadModalRef"
        :fileInfo="selectedFileInfo"
      />
      <!-- 申请使用弹窗 -->
      <ApplyDialog
        ref="applyDialogRef"
        @formSubmitted="handleFormSubmitted"
        :data-info="detailData"
      />
      <!-- 引入共享申请组件 -->
      <SharedApply
        ref="sharedApplyRef"
        :data-info="detailData"
        @formSubmitted="handleFormSubmitted"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import * as PortalApi from '@/api/portal'
import { getAccessToken } from '@/utils/auth'
import { useUserStoreWithOut } from '@/store/modules/user'
const emit = defineEmits(['formSubmitted'])
const route = useRoute()
const router = useRouter()

import ApplyDialog from './components/ApplyDialog.vue'
import DownloadAgreementModal from './components/DownloadAgreementModal.vue'
import ApplyDataModal from './components/ApplyDataModal.vue'
import SharedApply from './components/SharedApply.vue'

// 下载组件引用
const downloadModalRef = ref<InstanceType<typeof DownloadAgreementModal>>()
// 申请组件引用
const applyDataModalRef = ref<InstanceType<typeof ApplyDataModal>>()
// 申请弹窗引用
const applyDialogRef = ref<InstanceType<typeof ApplyDialog>>()
// 添加 SharedApply 组件引用
const sharedApplyRef = ref<InstanceType<typeof SharedApply>>()

// 选中的文件信息
const selectedFileInfo = ref({})

/* -------------------- 数据 -------------------- */
const detailData = reactive({
  catalogCode: '', // 目录编码
  menuName: '', // 目录分类名称
  catalogName: '', // 目录名称
  shareProperty: '', // 共享属性
  deptName: '', // 数源部门名称
  updateTime: '', // 更新时间
  applyScene: '', // 应用场景
  channel: '', // 提供渠道
  domain: '', // 所属领域
  periodType: '', // 更新频率
  abstractInfo: '', // 目录摘要
  businessDomain: '', // 业务领域
  subjectType: '', // 主题类型
  subjectFeature: '', // 主题特征
  industryClass: '', // 行业分类
  businessClass: '', // 业务分类
  manageObjClass: '', // 管理对象分类
  topicClass: '', // 主题分类
  infoCategoryClass: '', // 信息类别分类
  viewNum: '', // 查看次数
  interfaceStatus: '' // 接口状态
})

const headerList = ref([
  { name: '首页', path: '/', id: '1' },
  { name: '数据目录', path: '/dataCatalog', id: '2' },
  { name: '数据集', path: '/dataset', id: '3' },
  { name: '数据接口', path: '/dataInterface', id: '4' },
  { name: '用户中心', path: '/userCenter', id: '5' }
])

// 1. 首先，优化getShareTypeText函数，增强类型检查和错误处理
const getShareTypeText = (row: any, column: any, cellValue: any, index: number) => {
  // 优先使用cellValue，如果没有则从row中获取shareType
  const value = cellValue !== undefined ? cellValue : row?.shareType

  if (value == null || value === undefined || value === '') {
    return '暂无信息'
  }

  // 如果value是对象，尝试从中提取有用信息
  if (typeof value === 'object') {
    if (value.label) {
      return value.label
    }
    return '未知类型'
  }

  // 转换为字符串以便比较
  const stringValue = String(value)

  // 优先从已保存的活数据中查找
  if (shareTypeData.value && shareTypeData.value.length > 0) {
    const item = shareTypeData.value.find((item) => String(item.value) === stringValue)
    if (item) {
      return item.label
    }
  }

  // 作为后备方案
  if (shareTypeDefaultMap[stringValue]) {
    return shareTypeDefaultMap[stringValue]
  }

  return stringValue
}
// 添加响应式变量存储数据类型字典
const dataTypeDict = ref<any[]>([])

const fetchDataTypeDict = async () => {
  try {
    const response = await PortalApi.getDictByCode({ dictType: 'dataType' })
    if (response && Array.isArray(response)) {
      dataTypeDict.value = response
    }
  } catch (error) {
    console.error('获取数据类型字典失败:', error)
  }
}

// 创建数据类型格式化函数
const getDataTypeText = (row: any, column: any, cellValue: any, index: number) => {
  // 优先使用cellValue，如果没有则从row中获取type
  const value = cellValue !== undefined ? cellValue : row?.type

  if (value == null || value === undefined || value === '') {
    return '暂无信息'
  }

  // 如果value是对象，尝试从中提取有用信息
  if (typeof value === 'object') {
    if (value.label) {
      return value.label
    }
    return '未知类型'
  }

  // 转换为字符串以便比较
  const stringValue = String(value)

  // 从数据类型字典中查找对应的label
  if (dataTypeDict.value && dataTypeDict.value.length > 0) {
    const item = dataTypeDict.value.find((item) => String(item.value) === stringValue)
    if (item) {
      return item.label
    }
  }

  return stringValue
}
const detailDatas = reactive({
  serviceUrl: '', // 服务地址
  interfacePath: '', // 接口路径
  interfaceType: '', // 接口类型
  interfaceMethod: '', // 接口方法
  interfaceCode: '', // 接口编码
  contentType: '', // 内容类型
  requestExample: '', // 请求参数示例
  responseExample: '' // 返回参数示例
})

// 字典标签映射
const dictLabels = reactive<Record<string, string>>({})

// 存储从接口获取的共享类型活数据
const shareTypeData = ref<any[]>([])

// 用于共享属性的默认字典映射，作为API调用失败的后备方案
const shareTypeDefaultMap = {
  '1': '无条件共享',
  '2': '有条件共享',
  '3': '不予共享'
}

// 获取共享类型的中文标签
const getShareTypeLabel = computed(() => {
  // 优先使用通过API获取的字典值
  if (dictLabels.shareProperty) {
    return dictLabels.shareProperty
  }
  // 尝试从已保存的活数据中查找
  // console.log('shareTypeData', shareTypeData.value)

  if (detailData.shareProperty && shareTypeData.value.length > 0) {
    const item = shareTypeData.value.find((item) => item.value === detailData.shareProperty)
    if (item) {
      return item.label
    }
  }
  // 作为最后的后备方案
  if (detailData.shareProperty && shareTypeDefaultMap[detailData.shareProperty]) {
    return shareTypeDefaultMap[detailData.shareProperty]
  }
  return ''
})

// 获取当前路由路径对应的名称
const currentRouteName = computed(() => {
  const currentPath = route.path.split('/')[1] // 获取路由的第一部分
  const matchedRoute = headerList.value.find(
    (item) => item.path === `/${currentPath}` || item.path.includes(currentPath)
  )
  return matchedRoute ? matchedRoute.name : '数据目录'
})

// 获取当前路由路径
const currentRoutePath = computed(() => {
  const currentPath = route.path.split('/')[1]
  const matchedRoute = headerList.value.find(
    (item) => item.path === `/${currentPath}` || item.path.includes(currentPath)
  )
  return matchedRoute ? matchedRoute.path : '/dataCatalog'
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const previewData = ref([])
const tableColumns = ref<string[]>([])
// 存储接口方法字典数据
const interfaceMethodDict = ref<any[]>([])
// 存储显示的接口方法label
const interfaceMethodLabel = ref('')
// 添加加载状态变量
const loading = ref(true)

// 表格固定列配置
const columns = [
  { prop: 'name', label: '信息项名称' },
  { prop: 'type', label: '数据类型', formatter: getDataTypeText },
  // { prop: 'sensitiveLevel', label: '数据敏感级别' },
  { prop: 'sourceSystem', label: '来源系统' },
  { prop: 'shareType', label: '共享类型', formatter: getShareTypeText }
  // { prop: 'noneShare', label: '共享条件' }
]

/* -------------------- 申请使用相关状态 -------------------- */
const applyStatus = ref('apply') // apply: 申请使用, processing: 办理中, completed: 已办结

const applyStatusText = computed(() => {
  switch (applyStatus.value) {
    case 'apply':
      return '申请使用'
    case 'processing':
      return '办理中'
    case 'completed':
      return '已办结'
    default:
      return '申请使用'
  }
})

const openApplyDialog = () => {
  try {
    applyDialogRef.value.openAgreement()
  } catch (error) {
    console.error('登录状态验证失败，可能已过期', error)
  }
}

// 获取字典值对应的中文名称
const fetchDictValueLabel = async (dictType: string, dictValue: string): Promise<string> => {
  try {
    // 特殊处理shareType，如果已经有接口数据，优先从本地获取
    if (dictType === 'shareType' && shareTypeData.value.length > 0) {
      const item = shareTypeData.value.find((item) => item.value == dictValue)
      if (item) {
        return item.label
      }
    }

    const response = await PortalApi.getDictByCode({ dictType })

    // 如果是shareType，保存接口返回的数据
    if (dictType === 'shareType' && response && Array.isArray(response)) {
      shareTypeData.value = response
    }

    if (response && Array.isArray(response)) {
      // 先尝试精确匹配
      const item = response.find((item: any) => item.value === dictValue)
      if (item && item.label) {
        return item.label
      }
      // 如果没有精确匹配，可能是数值类型不匹配，尝试转换类型后匹配
      const numValue = String(dictValue)
      const numItem = response.find((item: any) => String(item.value) === numValue)
      if (numItem && numItem.label) {
        return numItem.label
      }
    }
  } catch (error) {
    console.error(`获取字典类型 ${dictType} 的值 ${dictValue} 对应的中文名称失败:`, error)
    // 对于shareType，尝试从已保存的活数据中查找
    if (dictType === 'shareType' && shareTypeData.value.length > 0) {
      const item = shareTypeData.value.find((item) => item.value === dictValue)
      if (item) {
        return item.label
      }
    }
    // 作为最后的后备方案
    if (dictType === 'shareType' && shareTypeDefaultMap[dictValue]) {
      return shareTypeDefaultMap[dictValue]
    }
  }
  return dictValue
}

// 批量获取所有需要的字典值对应的中文名称
const fetchAllDictLabels = async (data: any) => {
  const dictFields = [
    'businessDomain',
    'subjectType',
    'subjectFeature',
    'industryClass',
    'businessClass',
    'manageObjClass',
    'topicClass',
    'infoCategoryClass',
    'shareType'
  ]

  // 先单独获取shareType的完整数据列表
  try {
    const shareTypeResponse = await PortalApi.getDictByCode({ dictType: 'shareType' })
    if (shareTypeResponse && Array.isArray(shareTypeResponse)) {
      shareTypeData.value = shareTypeResponse
    }
  } catch (error) {
    console.error('获取共享类型完整数据失败:', error)
  }

  // 处理shareType字段
  if (data.shareProperty) {
    dictLabels['shareType'] = await fetchDictValueLabel('shareType', data.shareProperty)
  }

  // 再处理其他字典字段
  for (const field of dictFields) {
    if (data[field]) {
      dictLabels[field] = await fetchDictValueLabel(field, data[field])
    }
  }
}

// 格式化请求参数JSON
const formattedRequestParams = computed(() => {
  try {
    const parsed = JSON.parse(detailDatas.requestExample || '{}')
    return JSON.stringify(parsed, null, 2)
  } catch (error) {
    return detailDatas.requestExample || '{}'
  }
})

// 格式化返回参数JSON
const formattedResponseParams = computed(() => {
  try {
    const parsed = JSON.parse(detailDatas.responseExample || '{}')
    return JSON.stringify(parsed, null, 2)
  } catch (error) {
    return detailDatas.responseExample || '{}'
  }
})

/* -------------------- 获取数据详情 -------------------- */
const fetchDetailData = async () => {
  try {
    // 从路由参数中获取id
    const id = route.params.id as string

    if (!id) {
      console.error('未获取到数据ID')
      return
    }

    // 调用getResourceDirectoryById接口
    const response = await PortalApi.getResourceDirectoryById(id)

    if (response) {
      // 根据接口返回的数据结构更新detailData
      const apiData = response

      // 更新detailData对象，确保所有字段都被正确映射
      Object.assign(detailData, {
        catalogCode: apiData.catalogCode || '',
        menuName: apiData.menuName || '',
        catalogName: apiData.catalogName || '',
        shareProperty: apiData.shareProperty || '',
        deptName: apiData.deptName || '',
        updateTime: apiData.updateTime || '',
        applyScene: apiData.applyScene || '',
        channel: apiData.channel || '',
        domain: apiData.domain || '',
        periodType: apiData.periodType || '',
        abstractInfo: apiData.abstractInfo || '',
        businessDomain: apiData.businessDomain || '',
        subjectType: apiData.subjectType || '',
        subjectFeature: apiData.subjectFeature || '',
        industryClass: apiData.industryClass || '',
        businessClass: apiData.businessClass || '',
        manageObjClass: apiData.manageObjClass || '',
        topicClass: apiData.topicClass || '',
        infoCategoryClass: apiData.infoCategoryClass || '',
        // 额外的字段
        viewNum: apiData.viewNum || '',
        isCollection: apiData.isCollection || '',
        viewCount: apiData.viewCount || '',
        dataCount: apiData.dataCount || '',
        accessWay: apiData.accessWay || '',
        collected: apiData.isCollection || false,
        otherResource: apiData.otherResource || {},
        interfaceStatus: apiData.interfaceStatus
      })

      // 获取字典值对应的中文名称
      await fetchAllDictLabels(apiData)
    }
  } catch (error) {
    console.error('获取数据详情失败:', error)
    // 可以添加错误提示
  }
}

/* -------------------- 获取数据项 -------------------- */
// 确保表格数据包含shareType字段
const fetchCatalogInfo = async () => {
  try {
    const catalogId = route.params.id as string
    if (!catalogId) return
    previewData.value = []
    const response = await PortalApi.getCatalogInfo({
      catalogId,
      currentPage: currentPage.value,
      pageSize: pageSize.value
    })

    if (response) {
      // 确保数据包含shareType字段，如果没有则添加默认值
      previewData.value = (response.data || []).map((item: any) => ({
        ...item,
        shareType: item.shareType || item.shareProperty || '' // 尝试从不同字段获取
      }))
      total.value = response.totalCount || 0
    }
  } catch (error) {
    console.error('获取数据目录详情数据项失败:', error)
  }
}

/* -------------------- 获取接口基本信息详情 -------------------- */
const fetchInterfaceDetail = async () => {
  try {
    const catalogId = route.params.id as string
    if (!catalogId) return
    // 检查接口状态，只有状态为通过（4）时才调用接口

    // 先获取接口详情数据
    const response = await PortalApi.getInterfaceByCatalogId(catalogId)

    if (response) {
      // 更新接口详情数据
      Object.assign(detailDatas, {
        serviceUrl: response.serviceUrl || '', // 服务地址
        interfacePath: response.interfacePath || '', // 接口路径
        interfaceType: response.interfaceType || '', // 接口类型
        interfaceMethod: response.interfaceMethod || '', // 接口方法(原始值)
        interfaceCode: response.interfaceCode || '', // 接口编码
        contentType: response.contentType || '', // 内容类型
        requestExample: response.requestExample || '', // 请求参数示例
        responseExample: response.responseExample || '' // 返回参数示例
      })

      // 获取接口方法类型字典数据
      const shareTypeResponse = await PortalApi.getDictByCode({ dictType: 'jiekouType' })

      if (shareTypeResponse && shareTypeResponse.length > 0) {
        // 保存字典数据
        interfaceMethodDict.value = shareTypeResponse

        // 根据接口方法值查找对应的label
        const matchedItem = shareTypeResponse.find(
          (item: any) => item.value === response.interfaceMethod
        )

        // 设置显示的label，如果没有匹配项则使用原始值
        interfaceMethodLabel.value = matchedItem
          ? matchedItem.label
          : response.interfaceMethod || ''
      }
    }
  } catch (error) {
    console.error('获取接口详情失败:', error)
  }
}

/*  -------------------- 获取数据集数据下载列表 -------------------- */
const datasetList = ref<any[]>([])

interface SpanMethodProps {
  row: any
  column: any
  rowIndex: number
  columnIndex: number
}

let rowSpansMap = new Map() // 存储需要合并的行信息

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  // 定义需要合并的列索引（操作列的索引为4）
  const mergeColumns = [4]

  // 检查当前列是否需要合并
  if (mergeColumns.includes(columnIndex)) {
    const span = rowSpansMap.get(rowIndex)
    if (span) {
      return {
        rowspan: span,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

const initRowSpans = (data: any[]) => {
  // 清空之前的合并信息
  rowSpansMap.clear()

  // 如果没有数据，直接返回
  if (!data || data.length === 0) return

  // 根据业务需求，可以选择不同的合并条件
  // 这里我们假设根据status字段来合并行，相同status的行应该被合并
  let currentStatus = data[0].status
  let currentRowspan = 1

  for (let i = 1; i < data.length; i++) {
    if (data[i].status === currentStatus) {
      // 如果当前行的status与上一行相同，增加合并行数
      currentRowspan++
    } else {
      // 如果不同，记录上一组的合并信息
      rowSpansMap.set(i - currentRowspan, currentRowspan)
      // 重置当前的合并信息
      currentStatus = data[i].status
      currentRowspan = 1
    }
  }

  // 记录最后一组的合并信息
  rowSpansMap.set(data.length - currentRowspan, currentRowspan)
}

// 添加文件格式字典的响应式变量
const fileFormatDict = ref<Map<string, string>>(new Map())

// 获取文件格式字典数据
const fetchFileFormatDict = async () => {
  try {
    const response = await PortalApi.getDictByCode({ dictType: 'fileFormat' })
    if (response && Array.isArray(response)) {
      const formatMap = new Map<string, string>()
      response.forEach((item) => {
        formatMap.set(item.value, item.label)
      })
      fileFormatDict.value = formatMap
    }
  } catch (error) {
    console.error('获取文件格式字典失败:', error)
  }
}

const fetchDatasetDetail = async () => {
  try {
    const id = route.params.id as string
    if (!id) return
    // 先获取文件格式字典数据
    await fetchFileFormatDict()
    // 再获取数据集详情数据
    const response = await PortalApi.getDataSetById({ catalogId: id })

    if (response) {
      // 处理数据，添加格式化后的文件格式标签
      datasetList.value = (response || []).map((item) => ({
        ...item,
        // 添加文件格式标签，如果字典中没有对应的值则使用原始值
        fileFormatLabel: fileFormatDict.value.get(item.downloadType) || item.downloadType || '未知'
      }))

      initRowSpans(datasetList.value)
    }
  } catch (error) {
    console.error('获取数据集详情失败:', error)
  }
}

// 跳转到数据集详情页面
const toDatasetDetail = (rowData) => {
  // 构建完整的URL路径，格式为 /dataset/{id}
  const targetUrl = `/dataset/${route.params.id}`
  // 使用window.location.href进行页面刷新跳转
  window.location.href = targetUrl
}

// 跳转到接口详情页面
const toInterfaceDetail = (rowData) => {
  // 构建完整的URL路径，格式为 /interface/{id}
  const targetUrl = `/dataInterface/${route.params.id}`
  // 使用window.location.href进行页面刷新跳转
  window.location.href = targetUrl
}

// 打开下载流程
const openDownloadProcess = () => {
  // 如果是表格中的下载按钮，需要传入文件信息
  if (downloadModalRef.value) {
    downloadModalRef.value.openAgreement()
  }
}

const handleApplyDownloadAll = async () => {
  openDownloadProcess()
}

// 修改下载函数以处理不同类型的响应
const downloadFile = async (rowData) => {
  try {
    // 使用行数据中的真实参数
    const params = {
      downloadType: rowData.downloadType || '1',
      catalogId: rowData.catalogId || '',
      dataSourceId: rowData.dataSourceId || ''
    }

    // const params = {
    //   downloadType: '3',
    //   catalogId: '53201230',
    //   dataSourceId: '1234'
    // }

    // 发送下载请求
    const response = await PortalApi.downloadDataSetFile(params)

    // 判断响应类型并进行不同处理
    if (response && response instanceof Blob) {
      // 处理Blob对象（适用于Excel等文件类型）
      const contentType = response.type || 'application/octet-stream'
      const url = window.URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url

      let fileName = rowData.dataSourceName || 'data'

      // 根据文件类型设置扩展名
      if (contentType.includes('excel') || contentType.includes('spreadsheetml')) {
        if (!fileName.endsWith('.xlsx')) {
          fileName += '.xlsx'
        }
      } else if (contentType.includes('word')) {
        if (!fileName.endsWith('.docx')) {
          fileName += '.docx'
        }
      } else if (contentType.includes('pdf')) {
        if (!fileName.endsWith('.pdf')) {
          fileName += '.pdf'
        }
      } else if (contentType.includes('json')) {
        if (!fileName.endsWith('.json')) {
          fileName += '.json'
        }
      }

      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } else if (params.downloadType === '3' && response && typeof response === 'object') {
      // 特殊处理downloadType为3的情况（JSON数组数据）
      // 将JSON数据转换为字符串
      const jsonStr = JSON.stringify(response, null, 2)
      // 创建Blob对象
      const blob = new Blob([jsonStr], { type: 'application/json;charset=utf-8' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = (rowData.dataSourceName || 'data') + '.json'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } else {
      // 处理其他情况
      ElMessage.error('下载失败：返回的数据不是有效的文件')
      return
    }

    // 显示成功提示
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('文件下载失败:', error)
    ElMessage.error('文件下载失败，请重试')
  }
}

// 分页变化时触发
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchCatalogInfo()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  fetchCatalogInfo()
}

// 打开申请弹窗
const openApplyDataModal = () => {
  applyDataModalRef.value?.openAgreement()
}

const openSharedApplyDialog = (type: string, category: string) => {
  try {
    // 获取 catalogId
    const id = route.params.id

    // 只传递参数，不调用接口
    sharedApplyRef.value?.openDialog({ catalogId: id, applicationType: type, category: category })
  } catch (error) {
    console.error('打开申请弹窗失败：', error)
    ElMessage.error('打开申请弹窗失败，请稍后重试')
  }
}

const showInterface = ref(false)
const showDataset = ref(false)
const showDataCatalog = ref(false)
const isLogin = ref(true)

const refreshPageData = async () => {
  try {
    loading.value = true
    // 重新获取页面数据，这里可以调用原来的获取数据方法
    await Promise.all([fetchDetailData(), fetchCatalogInfo()])
    // ElMessage.success('页面已刷新')
  } catch (error) {
    console.error('刷新页面失败:', error)
    ElMessage.error('刷新页面失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleFormSubmitted = () => {
  refreshPageData()
}

// 添加测试接口弹窗相关状态
const testDialogVisible = ref(false)
const testParams = ref({})
const testResult = ref('')
const testLoading = ref(false)

const testOnlineInterface = () => {
  try {
    // 解析formattedRequestParams为可编辑的对象
    const parsedParams = JSON.parse(formattedRequestParams.value || '{}')
    testParams.value = parsedParams
    testResult.value = ''
    testDialogVisible.value = true
  } catch (error) {
    console.error('解析请求参数失败:', error)
    ElMessage.error('参数格式错误，请检查请求参数示例')
  }
}

// 提交测试请求
const submitTest = async () => {
  try {
    testLoading.value = true
    testResult.value = ''

    // 准备请求参数
    const requestData = {
      apiPath: detailDatas.interfacePath, // interfacePath映射到apiPath
      serverUrl: detailDatas.serviceUrl, // serviceUrl映射到serverUrl
      method: detailDatas.interfaceMethod == '1' ? 'POST' : 'GET', // interfaceMethod映射到method
      requestParams: testParams.value // 以Map<String, Object>格式传递修改后的值
    }

    let response
    // 根据interfaceMethod的值调用不同的接口
    if (detailDatas.interfaceMethod === '1') {
      // POST请求
      response = await PortalApi.getOnlinePost(requestData)
    } else {
      // GET请求
      response = await PortalApi.getOnlineGet(requestData)
    }

    // 格式化响应结果以便展示
    testResult.value = JSON.stringify(response, null, 2)
  } catch (error) {
    console.error('测试接口失败:', error)
    testResult.value = `测试失败: ${error.message || '未知错误'}`
    ElMessage.error('测试接口失败，请稍后重试')
  } finally {
    testLoading.value = false
  }
}

onMounted(async () => {
  try {
    // 设置加载状态为true
    loading.value = true

    // 检查用户是否登录
    const token = getAccessToken()
    isLogin.value = !!token

    const path = route.path.split('/')[1]
    showInterface.value = path === 'dataInterface'
    showDataset.value = path === 'dataset'
    showDataCatalog.value = path === 'dataCatalog'

    // 基本数据获取 - 不需要登录就可以调用
    await Promise.all([fetchDetailData(), fetchCatalogInfo()])

    // 以下接口需要登录才能调用
    const authPromises: any = []

    if (isLogin.value) {
      // 只有登录状态下才调用需要认证的API
      if (showInterface.value) {
        authPromises.push(fetchInterfaceDetail())
      }

      if (showDataset.value) {
        authPromises.push(fetchDatasetDetail())
      }
    }

    // 等待所有需要认证的请求完成
    if (authPromises.length > 0) {
      await Promise.all(authPromises)
    }

    // 最后获取数据类型字典
    await fetchDataTypeDict()
  } catch (error) {
    console.error('数据加载失败:', error)
  } finally {
    // 无论成功失败，都关闭加载动画
    loading.value = false
  }
})
</script>

<style scoped lang="scss">
.data-detail-container {
  padding: 16px;
  padding: 16px 80px;
  background: #eff4fa;
  min-height: 100vh;
  position: relative;

  .content-container {
    width: 100%;
    min-height: calc(100vh - 32px);
  }

  :deep(.el-loading-mask) {
    position: fixed !important; /* 固定定位覆盖整个屏幕 */
    top: 0 !important;
    left: 0 !important;
    z-index: 2050 !important; /* 确保在最上层 */
  }
  :deep(.el-loading-spinner) {
    padding: 20px !important;
  }

  :deep(.el-loading-spinner .circular) {
    width: 42px !important;
    height: 42px !important;
    margin-bottom: 10px !important;
  }

  // // 加载动画样式
  // .loading-container {
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   height: 200px;
  // }

  // .loading-spinner {
  //   display: flex;
  //   flex-direction: column;
  //   align-items: center;
  //   justify-content: center;
  //   padding: 20px;
  //   background: rgba(255, 255, 255, 0.9);
  //   border-radius: 8px;
  //   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  // }

  // .spinner {
  //   width: 40px;
  //   height: 40px;
  //   border: 3px solid #f3f3f3;
  //   border-top: 3px solid #009eff;
  //   border-radius: 50%;
  //   animation: spin 1s linear infinite;
  //   margin-bottom: 10px;
  // }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .loading-spinner p {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }

  .breadcrumb-section {
    margin-bottom: 16px;
    padding: 12px 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .main-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 16px;
    background: #fff;

    .card-header {
      background-image: url('@/assets/imgs/detail/background.png');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      padding: 20px 24px;
      border-radius: 8px 8px 0 0;
      margin: -16px -16px 0 -16px;
      position: relative;
      min-height: 120px;
      color: #fff; /* 设置文字颜色为白色，确保在背景图片上清晰可见 */

      .header-top {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-content {
          display: flex;
          .dataset-type {
            background: #009eff;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 12px;
            margin-right: 8px;
          }

          .dataset-title {
            margin: 0;
            font-size: 18px;
            color: #303133;
          }
        }

        .header-actions {
          display: flex;
          align-items: center;
          gap: 8px;

          .action-item {
            display: flex;
            align-items: center;
            gap: 4px;
            cursor: pointer;
          }

          img {
            width: 24px;
            height: 24px;
          }
        }
      }

      .header-bottom {
        display: flex;
        gap: 24px;
        align-items: center;
        margin-top: 20px;
        color: #666666;

        .bottom-item {
          display: flex;
          align-items: center;
          font-size: 14px;
          gap: 8px;

          img {
            width: 16px;
            height: 16px;
          }
        }
      }
    }

    .basic-info {
      // padding: 16px;

      .summary {
        min-width: 100px;
        max-width: 300px;
        color: #303133;
      }
      :deep(.el-descriptions__label) {
        background-color: #ffffff !important;
      }

      :deep(.el-descriptions__cell) {
        // border: 0;
        padding: 14px;
      }
    }

    // 接口调用指导样式
    .calling-guide-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30px 40px;
      margin: 20px 0;
      background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
      border-radius: 12px;
      border: 1px solid #e2e8f0;
      position: relative;
    }

    .step-item {
      display: flex;
      align-items: center;
      flex: 1;
      position: relative;
      z-index: 2;

      &:last-child {
        flex: none;
      }
    }

    .step-number {
      width: 32px;
      height: 32px;
      background: linear-gradient(135deg, #009eff 0%, #0077cc 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-weight: 600;
      font-size: 14px;
      margin-right: 12px;
      box-shadow: 0 4px 8px rgba(0, 158, 255, 0.3);
      position: relative;
      z-index: 3;
    }

    .step-content {
      background: white;
      border: 2px solid #e2e8f0;
      border-radius: 10px;
      padding: 16px 20px;
      text-align: center;
      min-width: 140px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: -6px;
        transform: translateY(-50%);
        width: 12px;
        height: 12px;
        background: white;
        border: 2px solid #e2e8f0;
        border-right: none;
        border-bottom: none;
        transform: translateY(-50%) rotate(-45deg);
        z-index: 1;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: #374151;
        font-weight: 500;
        line-height: 1.4;
        transition: all 0.3s ease;
      }
    }

    .step-item:hover .step-content {
      border-color: #009eff;
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(0, 158, 255, 0.15);

      p {
        color: #009eff;
      }
    }

    .step-arrow {
      flex: 1;
      margin: 0 20px;
      position: relative;
      height: 2px;

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(90deg, #e2e8f0 0%, #cbd5e1 50%, #e2e8f0 100%);
        transform: translateY(-50%);
      }

      &::after {
        content: '';
        position: absolute;
        top: 50%;
        right: 0;
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 6px 0 6px 8px;
        border-color: transparent transparent transparent #94a3b8;
        transform: translateY(-50%);
        transition: all 0.3s ease;
      }
    }

    // .step-item:hover + .step-item .step-arrow::before {
    //   background: linear-gradient(90deg, #009eff 0%, #0077cc 50%, #009eff 100%);
    // }

    // .step-item:hover + .step-item .step-arrow::after {
    //   border-color: transparent transparent transparent #009eff;
    // }

    // 请求和返回参数样式
    .request-params-section,
    .response-params-section {
      margin-top: 20px;
      padding: 0 20px;
      color: #303133;
    }

    .code-block {
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 20px;
      overflow-x: auto;
    }

    .code-block pre {
      margin: 0;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
    }

    .no-data {
      text-align: center;
      padding: 40px;
      color: #999;
      font-size: 14px;
    }

    .data-resource-section {
      background-image: url('@/assets/imgs/detail/dw_back.png');
      background-repeat: no-repeat;
      border-radius: 8px;
      margin: 16px 0;
      // min-height: 200px;
      position: relative;
      color: #fff;
      text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.7);

      .resource-content {
        padding: 24px;
        position: relative;
        display: flex;
        justify-content: space-between;
        z-index: 2;

        .resource-item {
          display: flex;
          align-items: center;
          gap: 8px;
          .resource-item-son {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }

        img {
          width: 16px;
          height: 16px;
        }

        h3 {
          font-size: 20px;
          margin-bottom: 12px;
          font-weight: bold;
        }

        p {
          font-size: 14px;
          line-height: 1.6;
          max-width: 600px;
        }
      }
    }

    .access-section,
    .preview-section {
      margin-top: 24px;

      :deep(.el-table) {
        tr {
          background-color: #ffffff;
        }
        .el-table__body {
          tr {
            background-color: #ffffff;
            height: 60px; /* 调整行高，可以根据需要修改这个值 */

            /* 确保鼠标悬停时没有颜色变化 */
            &:hover {
              background-color: #ffffff !important;
            }

            /* 确保单元格在悬停时也没有颜色变化 */
            &:hover > td {
              background-color: #ffffff !important;
            }

            td {
              padding: 16px 0; /* 调整单元格内边距 */
              background-color: #ffffff !important;
            }
          }
        }
      }
      :deep(.el-table__header) {
        // background-color: #eff4fa !important;

        th {
          background-color: #eff4fa !important;
          height: 60px;
        }

        tr {
          background-color: #ffffff;
        }
      }

      h3 {
        margin-bottom: 12px;
        font-size: 16px;
        color: #303133;
      }
    }
    .access-way {
      display: flex;
      align-items: center;
      gap: 8px;
      .label {
        color: #606266;
      }
    }
  }
}

.title-data {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 20px 0;
  color: #000000;

  .border-left {
    width: 6px;
    height: 24px;
    background: #009eff;
    border-radius: 3px 3px 3px 3px;
  }
}

.no-login-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background-color: #fafafa;
  border-radius: 8px;
  margin: 16px 0;

  .tip-content {
    text-align: center;

    .login-icon {
      width: 80px;
      height: 80px;
      margin-bottom: 16px;
      opacity: 0.5;
    }

    p {
      font-size: 16px;
      color: #606266;
      margin-bottom: 24px;
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.test-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.dialog-section {
  margin-bottom: 20px;
}

.dialog-section h4 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.params-editor {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.param-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.param-item:last-child {
  margin-bottom: 0;
}

.param-name {
  width: 160px;
  color: #606266;
  font-weight: 500;
}

.param-item :deep(.el-input) {
  flex: 1;
}

.result-container {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.result-container pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.no-params,
.no-result,
.loading {
  padding: 20px;
  text-align: center;
  color: #909399;
}
</style>
